/*
 * Copyright (c) 2013-2018 上海汇数数据. All rights reserved.
 * @(#) BaseSymmetricCipherApi.java 2018-08-06 17:26
 */

package cn.jh.common.core.crypto;

import javax.crypto.KeyGenerator;
import java.security.InvalidParameterException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;


/**
 * 对称密钥算法 {@code SymmetricCipherApi} 的基本实现。
 *
 * @author Fuchun
 * @since 1.0
 */
public abstract class BaseSymmetricCipherApi extends SymmetricCipherApi {

    protected BaseSymmetricCipherApi(SymmetricCipherParams params) {
        super(params);
    }

    public Key generateNewKey() {
        return generateNewKey(getParams().getKeySize());
    }

    public Key generateNewKey(int keySize) throws IllegalStateException, IllegalArgumentException {
        KeyGenerator kg;
        try {
            kg = KeyGenerator.getInstance(params.getAlgorithm(), params.getProvider());

            kg.init(keySize, ensureSecureRandom());
        } catch (NoSuchAlgorithmException ex) {
            throw new IllegalStateException("Not support `" + params.getAlgorithm() + "` algorithm on this platform");
        } catch (NoSuchProviderException ex) {
            throw new IllegalStateException("Not support `" + params.getProvider() + "` provider on this platform");
        } catch (InvalidParameterException ex) {
            throw new IllegalArgumentException("Invalid key size to use `" + params.getAlgorithm() + "` algorithm");
        }
        return kg.generateKey();
    }
}
